<?php

namespace Home\Model;

use Think\Model;

/**
 * 微信基础模型
 */
class WeixinModel extends Model {
	var $data = array ();
	var $wxcpt, $sReqTimeStamp, $sReqNonce, $sEncryptMsg;
	public function __construct() {
		if ($_REQUEST ['doNotInit'])
			return true;
		$content = wp_file_get_contents ( 'php://input' );
		! empty ( $content ) || die ( '这是微信请求的接口地址，直接在浏览器里无效' );
		
		if ($_GET ['encrypt_type'] == 'aes') {
			vendor ( 'WXBiz.wxBizMsgCrypt' );
			
			$this->sReqTimeStamp = I ( 'get.timestamp' );
			$this->sReqNonce = I ( 'get.nonce' );
			$this->sEncryptMsg = I ( 'get.msg_signature' );
			
			//$map ['id'] = I ( 'get.id' );
			$info = array();//M ( 'member_public' )->where ( $map )->find ();
			$info=array(
                'id'=>107,
                'uid'=>1,
                'public_name'=>'大学加',
                'public_id'=>'gh_009da023294d',
                'wechat'=>'wwwiiccn',
                'addon_config'=>'{"Wecome":{"type":"1","keyword":"","title":"","description":"\u73e0\u6d77\u5e02\u5927\u5b66\u52a0\u79d1\u6280\u6709\u9650\u516c\u53f8\u81f4\u529b\u4e8e\u5728\u6821\u5927\u5b66\u751f\u7684\u4e92\u8054\u7f51\u6280\u80fd\u57f9\u8bad\uff0c\u7279\u6709\u7684\u8bfe\u5802\u8bb2\u6388\u5168\u9762\u7684\u77e5\u8bc6\u4f53\u7cfb\u3001\u4e00\u5e26\u4e09\u5c0f\u56e2\u961f\u4f20\u627f\u72ec\u6709\u7ecf\u9a8c\u3001\u53c2\u4e0e\u9879\u76ee\u7814\u53d1\u8f7b\u677e\u6536\u83b7\u7a8d\u95e8\u6280\u5de7\uff0c\u4e09\u6761\u7ebf\u8def\u5b66\u4e60\u6709\u4fdd\u969c\u3002\r\n\u56de\u590d \u300e\u5ba2\u670d\u300f\u8f6c\u4eba\u5de5\u5ba2\u670d\uff1b\r\n\u56de\u590d\u300e\u9000\u51fa\u5ba2\u670d\u300f \u9000\u51fa\u4eba\u5de5\u5ba2\u670d\r\n\u56de\u590d\u300e\u62a5\u540d+\u624b\u673a\u53f7\u7801\u300f\u53ef\u62a5\u540d","pic_url":"","url":""},"Chat":{"tuling_key":"01155855eb654fd1680b8c6ca4b36e3d","tuling_url":" http:\/\/www.tuling123.com\/openapi\/api","simsim_key":"41250a68-3cb5-43c8-9aa2-d7b3caf519b1","simsim_url":"http:\/\/sandbox.api.simsimi.com\/request.p","rand_reply":"\u6ca1\u4e8b\u505a\u7684\u65f6\u5019\u591a\u5b66\u5b66\u4e92\u8054\u7f51\u5427\uff0c\u660e\u5929\u518d\u966a\u4f60\u804a\u5929\u5427\r\n\u54c8\u54c8~~\r\n\u4f60\u8bdd\u597d\u591a\u554a\uff0c\u4e0d\u8ddf\u4f60\u804a\u4e86\uff0c\u6211\u5f97\u53bb\u4e0a\u5927\u5b66\u52a0\u7684\u8bfe\u4e86\r\n\u867d\u7136\u4e0d\u61c2\uff0c\u4f46\u89c9\u5f97\u4f60\u8bf4\u5f97\u5f88\u5bf9\uff0c\u5927\u5b66\u52a0\u5b66\u5230\u7684\u5427"},"YouaskService":{"state":"1","zrg":"\u5ba2\u670d","model":"1","tcrg":"\u9000\u51fa\u5ba2\u670d"}}',
                'addon_status'=>'{"Coupon":0,"Test":0,"Exam":0,"Survey":0,"Leaflets":0,"WeiSite":0,"Card":0}',
                'token'=>'gh_009da023294d',
                'type'=>1,
                'appid'=>'wx25be63951ce8ac01',
                'secret'=>'22509a86d673bc5ca71e130cf8f3053b',
                'encodingaeskey'=>'ANZsqavTjesSjCE5MYmbdVjVTGsLaYOygN6rEi5IfRw',
            );
			get_token ( $info ['token'] ); // 设置token
			
			$this->wxcpt = new \WXBizMsgCrypt ( 'weiphp', $info ['encodingaeskey'], $info ['appid'] );
			
			$sMsg = ""; // 解析之后的明文
			$errCode = $this->wxcpt->DecryptMsg ( $this->sEncryptMsg, $this->sReqTimeStamp, $this->sReqNonce, $content, $sMsg );
			if ($errCode != 0) {
				addWeixinLog ( $_GET, "DecryptMsg Error: " . $errCode );
				exit ();
			} else {
				// 解密成功，sMsg即为xml格式的明文
				$content = $sMsg;
			}
		}
		
		$data = new \SimpleXMLElement ( $content );
		// $data || die ( '参数获取失败' );
		foreach ( $data as $key => $value ) {
			$this->data [$key] = strval ( $value );
		}
	}
	/* 获取微信平台请求的信息 */
	public function getData() {
		return $this->data;
	}
	/* ========================发送被动响应消息 begin================================== */
	/* 回复文本消息 */
	public function replyText($content) {
		$msg ['Content'] = $content;
		$this->_replyData ( $msg, 'text' );
	}
	/* 回复图片消息 */
	public function replyImage($media_id) {
		$msg ['Image'] ['MediaId'] = $media_id;
		$this->_replyData ( $msg, 'image' );
	}
	/* 回复语音消息 */
	public function replyVoice($media_id) {
		$msg ['Voice'] ['MediaId'] = $media_id;
		$msg ['Voice'] ['MediaId'] = $media_id;
		$this->_replyData ( $msg, 'voice' );
	}
	/* 回复视频消息 */
	public function replyVideo($media_id, $title = '', $description = '') {
		$msg ['Video'] ['MediaId'] = $media_id;
		$msg ['Video'] ['Title'] = $title;
		$msg ['Video'] ['Description'] = $description;
		$this->_replyData ( $msg, 'video' );
	}
	/* 回复音乐消息 */
	public function replyMusic($media_id, $title = '', $description = '', $music_url, $HQ_music_url) {
		$msg ['Music'] ['ThumbMediaId'] = $media_id;
		$msg ['Music'] ['Title'] = $title;
		$msg ['Music'] ['Description'] = $description;
		$msg ['Music'] ['MusicURL'] = $music_url;
		$msg ['Music'] ['HQMusicUrl'] = $HQ_music_url;
		$this->_replyData ( $msg, 'music' );
	}
	/*
	 * 回复图文消息 articles array 格式如下： array( array('Title'=>'','Description'=>'','PicUrl'=>'','Url'=>''), array('Title'=>'','Description'=>'','PicUrl'=>'','Url'=>'') );
	 */
	public function replyNews($articles) {
		$msg ['ArticleCount'] = count ( $articles );
		$msg ['Articles'] = $articles;
		
		$this->_replyData ( $msg, 'news' );
	}
	/* 发送回复消息到微信平台 */
	private function _replyData($msg, $msgType) {
		$msg ['ToUserName'] = $this->data ['FromUserName'];
		$msg ['FromUserName'] = $this->data ['ToUserName'];
		$msg ['CreateTime'] = NOW_TIME;
		$msg ['MsgType'] = $msgType;
		
		if($_REQUEST ['doNotInit']){
			dump($msg);
			exit;
		}
		
		$xml = new \SimpleXMLElement ( '<xml></xml>' );
		$this->_data2xml ( $xml, $msg );
		$str = $xml->asXML ();
		
		// 记录日志
		addWeixinLog ( $str, '_replyData' );
		
		if ($_GET ['encrypt_type'] == 'aes') {
			$sEncryptMsg = ""; // xml格式的密文
			$errCode = $this->wxcpt->EncryptMsg ( $str, $this->sReqTimeStamp, $this->sReqNonce, $sEncryptMsg );
			if ($errCode == 0) {
				$str = $sEncryptMsg;
			} else {
				addWeixinLog ( $str, "EncryptMsg Error: " . $errCode );
			}
		}
		
		echo ($str);
	}
	/* 组装xml数据 */
	public function _data2xml($xml, $data, $item = 'item') {
		foreach ( $data as $key => $value ) {
			is_numeric ( $key ) && ($key = $item);
			if (is_array ( $value ) || is_object ( $value )) {
				$child = $xml->addChild ( $key );
				$this->_data2xml ( $child, $value, $item );
			} else {
				if (is_numeric ( $value )) {
					$child = $xml->addChild ( $key, $value );
				} else {
					$child = $xml->addChild ( $key );
					$node = dom_import_simplexml ( $child );
					$node->appendChild ( $node->ownerDocument->createCDATASection ( $value ) );
				}
			}
		}
	}
	/* ========================发送被动响应消息 end================================== */
	/* 上传多媒体文件 */
	public function uploadFile($file, $type = 'image', $acctoken = '') {
		$post_data ['type'] = $type; // 媒体文件类型，分别有图片（image）、语音（voice）、视频（video）和缩略图（thumb）
		$post_data ['media'] = $file;
		
		$url = "http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token=$acctoken&type=image";
		$ch = curl_init ();
		curl_setopt ( $ch, CURLOPT_POST, 1 );
		curl_setopt ( $ch, CURLOPT_URL, $url );
		curl_setopt ( $ch, CURLOPT_POSTFIELDS, $post_data );
		ob_start ();
		curl_exec ( $ch );
		$result = ob_get_contents ();
		ob_end_clean ();
		
		return $result;
	}
	/* 下载多媒体文件 */
	public function downloadFile($media_id, $acctoken = '') {
		// TODO
	}
	/**
	 * GET 请求
	 *
	 * @param string $url        	
	 */
	private function http_get($url) {
		$oCurl = curl_init ();
		if (stripos ( $url, "https://" ) !== FALSE) {
			curl_setopt ( $oCurl, CURLOPT_SSL_VERIFYPEER, FALSE );
			curl_setopt ( $oCurl, CURLOPT_SSL_VERIFYHOST, FALSE );
		}
		curl_setopt ( $oCurl, CURLOPT_URL, $url );
		curl_setopt ( $oCurl, CURLOPT_RETURNTRANSFER, 1 );
		$sContent = curl_exec ( $oCurl );
		$aStatus = curl_getinfo ( $oCurl );
		curl_close ( $oCurl );
		if (intval ( $aStatus ["http_code"] ) == 200) {
			return $sContent;
		} else {
			return false;
		}
	}
	
	/**
	 * POST 请求
	 *
	 * @param string $url        	
	 * @param array $param        	
	 * @return string content
	 */
	private function http_post($url, $param) {
		$oCurl = curl_init ();
		if (stripos ( $url, "https://" ) !== FALSE) {
			curl_setopt ( $oCurl, CURLOPT_SSL_VERIFYPEER, FALSE );
			curl_setopt ( $oCurl, CURLOPT_SSL_VERIFYHOST, false );
		}
		if (is_string ( $param )) {
			$strPOST = $param;
		} else {
			$aPOST = array ();
			foreach ( $param as $key => $val ) {
				$aPOST [] = $key . "=" . urlencode ( $val );
			}
			$strPOST = join ( "&", $aPOST );
		}
		curl_setopt ( $oCurl, CURLOPT_URL, $url );
		curl_setopt ( $oCurl, CURLOPT_RETURNTRANSFER, 1 );
		curl_setopt ( $oCurl, CURLOPT_POST, true );
		curl_setopt ( $oCurl, CURLOPT_POSTFIELDS, $strPOST );
		$sContent = curl_exec ( $oCurl );
		$aStatus = curl_getinfo ( $oCurl );
		curl_close ( $oCurl );
		if (intval ( $aStatus ["http_code"] ) == 200) {
			return $sContent;
		} else {
			return false;
		}
	}
}